import sys

sys.path.insert(0, "..")
import time
import random

from opcua import ua, Server

if __name__ == "__main__":

    # setup our server
    server = Server()
    server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")

    # setup our own namespace, not really necessary but should as spec
    uri = "http://examples.freeopcua.github.io"
    idx = server.register_namespace(uri)

    # get Objects node, this is where we should put our nodes
    objects = server.get_objects_node()

    # populating our address space
    myobj = objects.add_object(idx, "MyObject")
    print("myobj: ", myobj)

    WindSpeed = myobj.add_variable(idx, "WindSpeed", 6.7)                # id=0
    WindDirection = myobj.add_variable(idx, "WindDirection", 6.7)
    ActivePower = myobj.add_variable(idx, "ActivePower", 6.7)
    GeneratorSpeed = myobj.add_variable(idx, "GeneratorSpeed", 6.7)
    GenertorTorq = myobj.add_variable(idx, "GenertorTorq", 6.7)
    PitchAngle = myobj.add_variable(idx, "PitchAngle", 6.7)
    TempAmbient = myobj.add_variable(idx, "TempAmbient", 6.7)
    WindDirectionToNorth = myobj.add_variable(idx, "WindDirectionToNorth", 6.7)
    DataEffecitveFlag = myobj.add_variable(idx, "DataEffecitveFlag", 6.7)
    HeartBeatFlagSever = myobj.add_variable(idx, "HeartBeatFlagSever", 6.7)   # id=9

    WindDirOffset = myobj.add_variable(idx, "WindDirOffset", 6.7)   # id=10
    PitchOffset = myobj.add_variable(idx, "PitchOffset", 6.7)
    KoptOffset = myobj.add_variable(idx, "KoptOffseet", 1.2)
    WindDirOffsetEnable = myobj.add_variable(idx, "WindDirOffsetEnable", 1)
    PitchOffsetEnable = myobj.add_variable(idx, "PitchOffsetEnable", 1)
    KoptOffsetEnable = myobj.add_variable(idx, "KoptOffsetEnable", 1)
    ClientHeartBeatFlag = myobj.add_variable(idx, "ClientHeartBeatFlag", 1)  # id=16

    #  Set MyVariable to be writable by clients
    WindDirOffset.set_writable()
    PitchOffset.set_writable()
    KoptOffset.set_writable()
    WindDirOffsetEnable.set_writable()
    PitchOffsetEnable.set_writable()
    KoptOffsetEnable.set_writable()
    ClientHeartBeatFlag.set_writable()


    # starting!
    server.start()

    try:
        count = 0
        while True:
            time.sleep(1)
            count += 0.1
            speed = random.uniform(3,10)
            WindSpeed.set_value(speed)
            GeneratorSpeed.set_value(speed * 260 + random.uniform(-10, 10))
            # GeneratorSpeed.set_value(random.uniform(1000, 1850))
            PitchAngle.set_value(random.uniform(-1,10))
            ActivePower.set_value(random.uniform(10,1000))
            HeartBeatFlagSever.set_value(int(count*10%5+1))

    finally:
        # close connection, remove subcsriptions, etc
        server.stop()
